package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.TcCheckinRecord;
import com.zhentao.pojo.TcNotice;
import com.zhentao.service.TcCheckinRecordService;
import com.zhentao.service.TcNoticeService;
import com.zhentao.config.Result;
import com.zhentao.config.PageResult;
import com.zhentao.config.OperationLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("tea/notice")
@Validated
public class NoticeController {

    @Autowired
    TcNoticeService noticeService;

    @Autowired
    TcCheckinRecordService checkinRecordService;

    /**
     * 获取全部通知
     */
    @GetMapping("list")
    public List<TcNotice> list(){
        return noticeService.list();
    }

    /**
     * 根据ID获取通知详情
     */
    @GetMapping("get/{id}")
    public TcNotice getById(@PathVariable Integer id){
        return noticeService.getById(id);
    }

    /**
     * 添加通知
     */
    @PostMapping("add")
    public Map<String, Object> add(@RequestBody TcNotice notice){
        Map<String, Object> result = new HashMap<>();
        try {
            notice.setCreateTime(new Date());
            boolean success = noticeService.save(notice);
            result.put("success", success);
            result.put("message", success ? "添加成功" : "添加失败");
            if (success) {
                result.put("data", notice);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新通知
     */
    @PutMapping("update")
    public Map<String, Object> update(@RequestBody TcNotice notice){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = noticeService.updateById(notice);
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
            if (success) {
                result.put("data", notice);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除通知
     */
    @DeleteMapping("delete/{id}")
    public Map<String, Object> delete(@PathVariable Integer id){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = noticeService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 根据发布者ID获取通知
     */
    @GetMapping("myNotices/{publisherUserId}")
    public List<TcNotice> getMyNotices(@PathVariable String publisherUserId){
        QueryWrapper<TcNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publisher_user_id", publisherUserId);
        queryWrapper.orderByDesc("create_time");
        return noticeService.list(queryWrapper);
    }

    /**
     * 根据班级ID获取通知
     */
    @GetMapping("classNotices/{classId}")
    public List<TcNotice> getClassNotices(@PathVariable String classId){
        QueryWrapper<TcNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("class_id", classId);
        queryWrapper.orderByDesc("is_top").orderByDesc("create_time");
        return noticeService.list(queryWrapper);
    }

    /**
     * 获取置顶通知
     */
    @GetMapping("topNotices")
    public List<TcNotice> getTopNotices(){
        QueryWrapper<TcNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_top", 1);
        queryWrapper.orderByDesc("create_time");
        return noticeService.list(queryWrapper);
    }

    /**
     * 搜索通知
     */
    @GetMapping("search")
    public List<TcNotice> searchNotices(@RequestParam String keyword){
        QueryWrapper<TcNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("title", keyword).or().like("content", keyword);
        queryWrapper.orderByDesc("create_time");
        return noticeService.list(queryWrapper);
    }

    /**
     * 批量删除通知
     */
    @DeleteMapping("batchDelete")
    public Map<String, Object> batchDelete(@RequestBody List<Integer> ids){
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = noticeService.removeByIds(ids);
            result.put("success", success);
            result.put("message", success ? "批量删除成功" : "批量删除失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 设置置顶
     */
    @PutMapping("setTop/{id}")
    public Map<String, Object> setTop(@PathVariable Integer id, @RequestParam Integer isTop){
        Map<String, Object> result = new HashMap<>();
        try {
            TcNotice notice = noticeService.getById(id);
            if (notice != null) {
                notice.setIsTop(isTop);
                boolean success = noticeService.updateById(notice);
                result.put("success", success);
                result.put("message", success ? "设置成功" : "设置失败");
            } else {
                result.put("success", false);
                result.put("message", "通知不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置失败：" + e.getMessage());
        }
        return result;
    }

    //获取打卡明细
    @RequestMapping("checkInRecordList")
    public List<TcCheckinRecord> list1(){
        return checkinRecordService.list();
    }

    /**
     * 分页查询通知
     */
    @GetMapping("page")
    public Result<PageResult<TcNotice>> getNoticePage(@RequestParam(defaultValue = "1") Integer current,
                                                      @RequestParam(defaultValue = "10") Integer size,
                                                      @RequestParam(required = false) String keyword,
                                                      @RequestParam(required = false) Integer classId,
                                                      @RequestParam(required = false) Integer isTop) {
        try {
            Page<TcNotice> page = new Page<>(current, size);
            QueryWrapper<TcNotice> queryWrapper = new QueryWrapper<>();
            
            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                queryWrapper.like("title", keyword).or().like("content", keyword);
            }
            
            // 班级筛选
            if (classId != null) {
                queryWrapper.eq("class_id", classId);
            }
            
            // 置顶筛选
            if (isTop != null) {
                queryWrapper.eq("is_top", isTop);
            }
            
            queryWrapper.orderByDesc("is_top").orderByDesc("create_time");
            
            Page<TcNotice> result = noticeService.page(page, queryWrapper);
            
            PageResult<TcNotice> pageResult = PageResult.of(
                (int) result.getCurrent(),
                (int) result.getSize(),
                result.getTotal(),
                result.getRecords()
            );
            
            return Result.success("分页查询通知成功", pageResult);
        } catch (Exception e) {
            return Result.error("分页查询通知失败：" + e.getMessage());
        }
    }

    /**
     * 发布通知
     */
    @PostMapping("publish")
    @OperationLog(value = "发布通知", type = "发布", module = "通知管理")
    public Result<TcNotice> publishNotice(@Valid @RequestBody TcNotice notice) {
        try {
            notice.setCreateTime(new Date());
            notice.setIsTop(0); // 默认不置顶
            boolean success = noticeService.save(notice);
            
            if (success) {
                return Result.success("通知发布成功", notice);
            } else {
                return Result.error("通知发布失败");
            }
        } catch (Exception e) {
            return Result.error("通知发布失败：" + e.getMessage());
        }
    }

    /**
     * 获取未读通知数量
     */
    @GetMapping("unreadCount/{userId}")
    public Result<Map<String, Object>> getUnreadCount(@PathVariable Integer userId) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 这里需要根据实际的阅读记录表来统计未读数量
            // 暂时返回0，实际项目中需要实现阅读记录功能
            result.put("unreadCount", 0);
            
            return Result.success("获取未读通知数量成功", result);
        } catch (Exception e) {
            return Result.error("获取未读通知数量失败：" + e.getMessage());
        }
    }

    /**
     * 标记通知为已读
     */
    @PutMapping("markAsRead/{noticeId}/{userId}")
    @OperationLog(value = "标记通知已读", type = "阅读", module = "通知管理")
    public Result<String> markAsRead(@PathVariable Integer noticeId, @PathVariable Integer userId) {
        try {
            // 这里需要实现阅读记录功能
            // 暂时返回成功，实际项目中需要操作阅读记录表
            return Result.success("标记已读成功");
        } catch (Exception e) {
            return Result.error("标记已读失败：" + e.getMessage());
        }
    }

    /**
     * 获取通知统计信息
     */
    @GetMapping("statistics")
    public Result<Map<String, Object>> getNoticeStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 总通知数
            long totalNotices = noticeService.count();
            statistics.put("totalNotices", totalNotices);
            
            // 置顶通知数
            QueryWrapper<TcNotice> topQuery = new QueryWrapper<>();
            topQuery.eq("is_top", 1);
            long topNotices = noticeService.count(topQuery);
            statistics.put("topNotices", topNotices);
            
            // 今日发布通知数
            QueryWrapper<TcNotice> todayQuery = new QueryWrapper<>();
            todayQuery.ge("create_time", new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000));
            long todayNotices = noticeService.count(todayQuery);
            statistics.put("todayNotices", todayNotices);
            
            return Result.success("获取通知统计信息成功", statistics);
        } catch (Exception e) {
            return Result.error("获取通知统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 批量发布通知
     */
    @PostMapping("batchPublish")
    @OperationLog(value = "批量发布通知", type = "发布", module = "通知管理")
    public Result<Map<String, Object>> batchPublishNotices(@RequestBody List<TcNotice> notices) {
        try {
            Map<String, Object> result = new HashMap<>();
            int successCount = 0;
            int failCount = 0;
            
            for (TcNotice notice : notices) {
                try {
                    notice.setCreateTime(new Date());
                    notice.setIsTop(0);
                    if (noticeService.save(notice)) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    failCount++;
                }
            }
            
            result.put("successCount", successCount);
            result.put("failCount", failCount);
            result.put("totalCount", notices.size());
            
            return Result.success("批量发布完成", result);
        } catch (Exception e) {
            return Result.error("批量发布失败：" + e.getMessage());
        }
    }
}
